From ade8a556af40d67e0762809d5136db8f3b4b3d09 Mon Sep 17 00:00:00 2001
From: Sebastian Rasmussen <sebras@gmail.com>
Date: Wed, 10 Mar 2021 01:38:44 +0100
Subject: [PATCH] Bug 703653: jbig2dec: Use correct freeing function for JBIG2
 images.

When jbig2_image_compose() errors out, remember to release all allocated
pattern images. Previously the most recently allocated image would not
be release.

Finally remember to free the array of images itself.
---
 jbig2_halftone.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/jbig2_halftone.c b/jbig2_halftone.c
index 9c275f2..78902f8 100644
--- a/jbig2_halftone.c
+++ b/jbig2_halftone.c
@@ -73,8 +73,10 @@ jbig2_hd_new(Jbig2Ctx *ctx, const Jbig2PatternDictParams *params, Jbig2Image *im
             new->patterns[i] = jbig2_image_new(ctx, HPW, HPH);
             if (new->patterns[i] == NULL) {
                 jbig2_error(ctx, JBIG2_SEVERITY_WARNING, JBIG2_UNKNOWN_SEGMENT_NUMBER, "failed to allocate pattern element image");
+                /* new->patterns[i] above did not succeed, so releasing patterns 0..i-1 is enough */
                 for (j = 0; j < i; j++)
-                    jbig2_free(ctx->allocator, new->patterns[j]);
+                    jbig2_image_release(ctx, new->patterns[j]);
+                jbig2_free(ctx->allocator, new->patterns);
                 jbig2_free(ctx->allocator, new);
                 return NULL;
             }
@@ -84,8 +86,10 @@ jbig2_hd_new(Jbig2Ctx *ctx, const Jbig2PatternDictParams *params, Jbig2Image *im
             code = jbig2_image_compose(ctx, new->patterns[i], image, -i * (int32_t) HPW, 0, JBIG2_COMPOSE_REPLACE);
             if (code < 0) {
                 jbig2_error(ctx, JBIG2_SEVERITY_WARNING, JBIG2_UNKNOWN_SEGMENT_NUMBER, "failed to compose image into collective bitmap dictionary");
-                for (j = 0; j < i; j++)
-                    jbig2_free(ctx->allocator, new->patterns[j]);
+                /* new->patterns[i] above succeeded, so release all patterns 0..i */
+                for (j = 0; j <= i; j++)
+                    jbig2_image_release(ctx, new->patterns[j]);
+                jbig2_free(ctx->allocator, new->patterns);
                 jbig2_free(ctx->allocator, new);
                 return NULL;
             }
